package com.lsy.weizhi2.activity;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lsy.weizhi2.JsonObject.ActivityListObject;
import com.lsy.weizhi2.JsonObject.ReplyList;
import com.lsy.weizhi2.R;
import com.lsy.weizhi2.adapter.ActivityDetailAdapter;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.config.CostomFlag;
import com.lsy.weizhi2.config.MyHeight;
import com.lsy.weizhi2.customview.ReplyDailog;
import com.lsy.weizhi2.mybase.MyBaseActivity;
import com.lsy.weizhi2.mybase.MyTitleView;
import com.lsy.weizhi2.mysql.MySQLOperate;
import com.lsy.weizhi2.myutils.DetailAdapterCall;
import com.lsy.weizhi2.myutils.FenXiangPopupCall;
import com.lsy.weizhi2.myutils.NoteDetailUPCall;
import com.lsy.weizhi2.myutils.ReplyDailogCall;
import com.lsy.weizhi2.myutils.UserInfoCall;
import com.lsy.weizhi2.popupwindow.DialogPopup;
import com.lsy.weizhi2.popupwindow.FenXiangPopup;
import com.lsy.weizhi2.utils.MyMethod;
import com.lsy.weizhi2.utils.MyOkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActivityDetail extends MyBaseActivity implements View.OnClickListener {
    private Context context;
    private MyTitleView activity_detail;
    private RecyclerView activity_detail_rv;
    private ActivityDetailAdapter activityDetailAdapter;
    private TextView activity_detail_gengduo, activity_detail_baoming;
    private ActivityListObject.ListBean bean;
    private Gson gson;
    private ReplyList replyList;
    private List<ReplyList.ListBean> list_r;
    private int pageNo = 1;

    private int xx;
    private FenXiangPopup fenXiangPopup;
    private RelativeLayout gengduo_rl, activity_detail_view;
    private ReplyDailog reply_dialog;
    private DialogPopup dialogpopup;
    private Handler handler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity_detail);
        context = ActivityDetail.this;
        Init();
    }

    @Override
    protected void onStart() {
        super.onStart();

        activityDetailAdapter.setDetailAdapterCall(new DetailAdapterCall() {
            @Override
            public void UPClick(View view, int flag) {
                switch (flag) {
                    case UserInfoCall.FOLLOW://调用收藏活动接口
                        ShouCang2();
                        break;
                    case UserInfoCall.IMAGE: //跳转用户信息界面
                        break;
                    case NoteDetailUPCall.BAOMING://报名
                        BaoMing();
                        break;
                }
            }

            @Override
            public void Receive() {
                pageNo=1;
                getReplyList();
            }

            @Override
            public void JuBaoOrPingBi(int flag, int position) {

            }
        });
    }

    /**
     * 收藏活动
     */
    private void ShouCang2(){
        MyOkHttpUtils.getInstance(context).doPost(Constants.ShouCang2+bean.getId(),null)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if(message!=null){
                            try {
                                JSONObject jsonObject=new JSONObject(message);
                                boolean resutl=jsonObject.getBoolean("result");
                                if(resutl){
                                    MyMethod.ShowDialog(context,"收藏成功");
                                }else{
                                    MyMethod.ShowDialog(context,jsonObject.getString("message"));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    /**
     * 界面显示
     */
    @Override
    protected void onResume() {
        super.onResume();
        xx = 0;
        ViewTreeObserver vto = activity_detail.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (xx < 1) {
                    xx++;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(activity_detail.getLayoutParams());
                            params.height = MyHeight.ACTIONBAR + MyHeight.MyTitleHeight;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                activity_detail.setLayoutParams(params);
                            }
                        }
                    });
                }
            }
        });
        activity_detail_rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                boolean islast = activity_detail_rv.canScrollVertically(1);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && !islast) {
                    if (list_r.size() == (pageNo) * 10) {
                        activityDetailAdapter.UpData(list_r, true, 2);
                    } else {
                        activityDetailAdapter.UpData(list_r, true, 3);
                    }
                } else {
                    if (list_r.size() == (pageNo) * 10) {
                        activityDetailAdapter.UpData(list_r, true, 1);
                        pageNo++;
                        getReplyList();
                    } else {
                        activityDetailAdapter.UpData(list_r, true, 3);
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                activityDetailAdapter.UpData(list_r, false, 0);
                            }
                        }, 1000);
                    }

                    // gengduo_rl.setVisibility(View.GONE);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        pageNo=1;
        getReplyList();
    }

    /**
     * 分页请求回复数据
     */
    private void getReplyList() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo + "");
        map.put("pageSize", "10");
        MyOkHttpUtils.getInstance(context).doGet(Constants.SELECT_ACTIVTY_REPLY + bean.getId() + "/reply", map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        Log.i("ActivityDetail", "message====222222===" + message);
                        replyList = gson.fromJson(message, ReplyList.class);
                        if (pageNo == 1) {
                            list_r.clear();
                        }
                        List<ReplyList.ListBean> list = replyList.getList();
                        if (list != null && list.size() != 0) {
                            list_r.addAll(list);
                            activityDetailAdapter.UpData(list_r, false, 0);
                        } else {
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    activityDetailAdapter.UpData(list_r,false,0);
                                }
                            },1000);
                        }

                    }
                });
    }

    @Override
    public void onPause() {
        super.onPause();
        xx = 0;
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    private void Init() {
        fenXiangPopup = new FenXiangPopup();
        gson = new Gson();
        list_r = new ArrayList<>();
        String json = getIntent().getStringExtra("json");
        if (json != null) {
            bean = gson.fromJson(json, ActivityListObject.ListBean.class);
        } else {
            bean = MySQLOperate.getInstance(context).Select_Activity(CostomFlag.Activity_Flag);
        }
        activity_detail = (MyTitleView) findViewById(R.id.activity_detail);
        activity_detail_rv = (RecyclerView) findViewById(R.id.activity_detail_rv);
        activity_detail_gengduo = (TextView) findViewById(R.id.activity_detail_gengduo);
        activity_detail_baoming = (TextView) findViewById(R.id.activity_detail_baoming);
        gengduo_rl = (RelativeLayout) findViewById(R.id.gengduo_rl);
        activity_detail_view = (RelativeLayout) findViewById(R.id.activity_detail_view);
        reply_dialog = (ReplyDailog) findViewById(R.id.reply_dialog);
        LinearLayoutManager manager = new LinearLayoutManager(context);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        activity_detail_rv.setLayoutManager(manager);
        activityDetailAdapter = new ActivityDetailAdapter(context, bean);
        activity_detail_rv.setAdapter(activityDetailAdapter);
        activity_detail_baoming.setOnClickListener(this);
        gengduo_rl.setOnClickListener(this);
        reply_dialog.setReplyDailogCall(new ReplyDailogCall() {
            @Override
            public void onClick(View view, int flag) {
                switch (flag) {
                    case ReplyDailogCall.CANCEL://点击取消关闭对话框
                        reply_dialog.setVisibility(View.GONE);
                        break;
                    case ReplyDailogCall.OK:
                        //点击确定发送消息并关闭对话框
                        String reply_info = reply_dialog.getText();
                        ReceiveActivity(bean.getId() + "", reply_info);
                        reply_dialog.setVisibility(View.GONE);
                        break;
                }
            }
        });
        fenXiangPopup.setFenXiangPopupCall(new FenXiangPopupCall() {
            @Override
            public void dismissListener() {
                HideFenXiang();
            }

            @Override
            public void onClick(View view, int flag) {
                //分享
                switch (flag) {
                    case FenXiangPopupCall.QQ:

                        MyMethod.toActivity(context, WebActivity.class);
                        // DialogPopup.ShowDialog(context,activity_detail_view,"分享QQ","确定分享",null);
                        break;
                    case FenXiangPopupCall.QQ2:

                        DialogPopup.ShowDialog(context, activity_detail_view, "分享QQ动态", "确定分享", null);
                        break;
                    case FenXiangPopupCall.WEIXIN:
                        DialogPopup.ShowDialog(context, activity_detail_view, "分享微信", "确定分享", null);
                        break;
                    case FenXiangPopupCall.WEIXIN2:
                        DialogPopup.ShowDialog(context, activity_detail_view, "分享微信朋友圈", "确定分享", null);
                        break;
                    case FenXiangPopupCall.WEIBO:
                        DialogPopup.ShowDialog(context, activity_detail_view, "分享微博", "确定分享", null);
                        break;
                    case FenXiangPopupCall.WEIBO2:
                        DialogPopup.ShowDialog(context, activity_detail_view, "分享人人网", "确定分享", null);
                        break;
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.activity_detail_baoming:
                //ShowFenXiang();
                BaoMing();
                break;
            case R.id.gengduo_rl://回复活动
                reply_dialog.setVisibility(View.VISIBLE);
                break;
        }
    }

    public void HideFenXiang() {
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 1.0f;
        getWindow().setAttributes(params);
    }

    private void ShowFenXiang() {
        fenXiangPopup.init(context, activity_detail_view);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
    }

    /**
     * 报名活动
     */
    private void BaoMing(){
        MyOkHttpUtils.getInstance(context).doPost(Constants.ActivityBaoMing+bean.getId()+"/registration",null)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if(message!=null){
                            try {
                                JSONObject jsonObject=new JSONObject(message);
                                boolean result=jsonObject.getBoolean("result");
                                if(result){
                                    MyMethod.ShowDialog(context,"报名成功");
                                }else{
                                    MyMethod.ShowDialog(context,jsonObject.getString("message"));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    /**
     * 回复活动
     * @param activity_id
     * @param content
     */
    private void ReceiveActivity(String activity_id, String content) {
        Map<String, String> map = new HashMap<>();
        map.put("activityId", activity_id);
        map.put("content", content);
        MyOkHttpUtils.getInstance(context).doPost(Constants.RECEIVE_ACTIVITY, map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        Log.i("ActivityDetail", "message=receive=" + message);
                        pageNo=1;
                        getReplyList();
                    }
                });
    }
}
